import { handleLogout } from '@/utils'

const baseUrl = '' // 基础路径

export default async (url = '', data: any = {}, type = 'GET', formData = '') => {
  type = type.toUpperCase() // 请求方式小写转换成大写
  url = baseUrl + url // 请求地址的拼接

  const requestConfig: any = {
    credentials: 'same-origin',
    method: type,
    headers: {
      Accept: '*/*',
      'Content-Type': 'application/json',
      'Access-Token': localStorage.getItem('token') || ''
    },
    mode: 'cors', // 用来决定是否允许跨域请求  值有 三个 same-origin，no-cors（默认）以及 cores;
    cache: 'force-cache' // 是否缓存请求资源 可选值有 default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。
  }

  if (type === 'GET') {
    let dataStr = '' //数据拼接字符串
    Object.keys(data).forEach((key) => {
      dataStr += key + '=' + data[key] + '&'
    })
    if (dataStr !== '') {
      dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
      url = url + '?' + dataStr
    }
  }

  if (type === 'DELETE') {
    const value = Object.values(data)[0]
    if (Array.isArray(value)) {
      requestConfig.body = JSON.stringify(data)
    } else {
      url = url + '/' + value
    }
  }

  if (['POST', 'PUT'].includes(type)) {
    requestConfig.body = JSON.stringify(data)
  }

  if (formData) {
    const formData = new FormData()
    for (const key in data) {
      formData.append(key, data[key])
    }
    delete requestConfig.headers['Content-Type']
    requestConfig.body = formData
  }

  try {
    const response = await fetch(url, requestConfig)
    const { code, data, message } = await response.json()
    if (code === 0) {
      return data
    }
    const msg = message || '服务器出错了'
    ElMessage.error(msg)
    if (code === 401) {
      handleLogout()
    }
    return Promise.reject(msg)
  } catch (error: any) {
    throw new Error(error)
  }
}
